package com.manage.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.manage.common.util.dateFunction.DateUtil;
import com.manage.mapper.single.StaffMapper;

import com.manage.model.dto.StaffExcel;
import com.manage.model.po.Staff;
import com.manage.model.dto.StaffDTO;
import com.manage.service.StaffService;
import com.manage.common.util.FileOptionUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 导出员工信息实现类
 * @author duaiyu
 * @version V1.0
 * @date 2022/2/20
 * 来源：自研
 */
@Service
public class StaffServiceImpl implements StaffService {
    @Resource
    StaffMapper staffMapper;

    int index;
    /**
     * 查询全部staff
     */
    @Override
    public List<Staff> queryStaff() {
        return staffMapper.queryStaff(9990);
    }

    /**
     * 将staff信息导出
     */
    @Override
    public String exportStaff() {
        //查询要导出数据的总数
        Integer count = staffMapper.countStaff();
        //要导出的指定路径
        String path = "E:\\excel";
        //创建路径
        String createPath = FileOptionUtil.createFile(path);
        //文件名 注意文件名后面不加/，就会输出文件名为excelstaff
        //String fileName = createPath + "\\staff.xlsx";
        String fileName = FileOptionUtil.getFileName(createPath);

        //查询需要执行多少次
        int runCount = threadRunCount(count);
        //线程执行
        threadRunBusiness(runCount, fileName);

//        try{
//            writer = EasyExcel.write(fileName, Staff.class).build();
//            WriteSheet writeSheet = EasyExcel.writerSheet("员工信息").build();
//            for(int i = 1; i <= 2; i++){
//                int start = i*10000 - 10000;
//                List<Staff> list = distributedQuery(start);
//                //向excel中写数据
//                writer.write(list, writeSheet);
//            }
//        }finally {
//            if(writer != null){
//                writer.finish();
//            }
//        }
        return fileName;
    }

    //线程执行业务
    private void threadRunBusiness(int runCount, String fileName){
        ThreadPoolExecutor thread = new ThreadPoolExecutor(10,50,
                3, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024),
                new ThreadPoolExecutor.AbortPolicy());
        if(runCount > 0){
            ExcelWriter writer = null;
            /**
             * 导出的慢，不是因为导出时候慢，一般情况导出用easyexcel就可以了。在很多时候，是因为查询的慢。
             * 所以，更多时候应该解决的是查询速度，当数据量大的时候，查询的内容又很多，建议使用
             * 中间件盛放查询结果，导出的时候，每次从中间件里面分布获取。因此这里不做具体导出
             */
            try{
                writer = EasyExcel.write(fileName, Staff.class).build();
                WriteSheet writeSheet = EasyExcel.writerSheet("员工信息").build();
                for(int i = 1; i <= 2; i++){
                    int start = i*10000 - 10000;
                    List<Staff> list = distributedQuery(start);
                    //向excel中写数据
                    writer.write(list, writeSheet);
                }
            }finally {
                if(writer != null){
                    writer.finish();
                }
            }
        }
    }

    //线程需要执行的次数
    private int threadRunCount(Integer count){
        int integer = count/10000;
        int decimal = count%10000;
        if(decimal > 0){
            integer ++;
        }
        if(integer == 0 && decimal == 0){
            integer = 0;
        }
        return integer;
    }

    //分布查询全部员工
    private List<Staff> distributedQuery(int start){
        //将要导出的信息查询出来   大量数据分批次查询
        List<Staff> queryStaff = staffMapper.queryStaff(start);
        return queryStaff;
    }

    @Override
    public Integer addStaff(StaffDTO staff) {
        return staffMapper.addStaff(staff);
    }

    @Override
    public String exportComplexStaff() {
        //要导出的指定路径
        String path = "E:\\excel";
        //创建路径
        String createPath = FileOptionUtil.createFile(path);
        //导出路径和文件名
        String pathName = FileOptionUtil.getFileName(createPath);

        //模板文件名
        String templateName = "export.xlsx";
        //模板文件路径
        String templateResource = getResource() + templateName;

        Map<String, Object> data = new HashMap<>();
        //模板显示系统当前时间
        data.put("date", DateUtil.getNowDate());
        //查询数据
        List<StaffExcel> list = staffMapper.exportComplexStaff();
        ExcelWriter excelWriter = null;
        try{
            excelWriter = EasyExcel.write(pathName).withTemplate(templateResource).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            // 导出表头时间
            excelWriter.fill(data, writeSheet);
            excelWriter.fill(list, writeSheet);
        } finally {
            excelWriter.finish();
        }
        return pathName;
    }

//    public static void main(String[] args) {
//        StaffServiceImpl im = new StaffServiceImpl();
//        System.out.println("im=" + im.getResource());
//    }

    public String getResource(){
        String FilePath = StaffServiceImpl.class.getResource("/").getPath();
        String templatePath = FilePath + "excel/";
        System.out.println("str{}"+templatePath);
        return templatePath;
    }
}
